package com.cn.shuangzi.ad.activity;


import android.os.Handler;
import android.view.View;

import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.manager.AdSplashManager;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.tt.SplashShownManager;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.kwad.sdk.api.KsSplashScreenAd;
import com.qq.e.ads.splash.SplashAD;

import java.util.List;

/**
 * 开屏广告Activity示例
 */
public abstract class GroMoreSplashActivity extends SZSplashActivity {

    private String mAdUnitId = "";
    private AdSplashManager mAdSplashManager;
    private TTSplashAd.AdInteractionListener mAdInteractionListener;
    private boolean isAdShown;
    private int SPLASH_SHOW_TIME_NORMAL = 1500;
    private long beginTime;
    private Handler handlerCloseSplash;
    private boolean isDealToNext = false;
    private boolean isForceClose;
    private boolean isClickAd;

    @Override
    public void onPreCreated() {
        isForceClose = false;
        isClickAd = false;
        resetSplashManager();
        initCutDown();
    }

    public void init(boolean isShowAd) {
        init(isShowAd, 1000);
    }

    public void init(boolean isShowAd, long delayToMain) {
        SZApp.getInstance().init();
        dealAd(isShowAd, delayToMain);
    }

    public void dealAd(boolean isShowAd) {
        dealAd(isShowAd, 1000);
    }

    public void dealAd(boolean isShowAd, long delayToMain) {
        if (isShowAd) {
            autoCloseSplash();
            ADUtil.logError("设置自动关闭成功");
            fetchSplashAD();
        } else {
            ADUtil.logError("不展示广告，直接进主页");
            toMain(delayToMain);
        }
    }
    private void resetSplashManager(){
        SplashShownManager.getInstance().setSplashShown(false);
    }


    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode(this)), onSplashADLoadListener);
    }

    private void fetchSplashAD() {

        beginTime = System.currentTimeMillis();
        mAdUnitId = getAdUnitId();

        initListener();
        initAdLoader();
        resetSplashManager();
        ADManager.getInstance().getSplash(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode(this)), new ADManager.OnSplashADLoadListener() {
            @Override
            public void onFetchAdSuccess(List<ADPlatform> adPlatformList) {
                if(SZValidatorUtil.isValidList(adPlatformList)) {
                    if (mAdSplashManager != null) {
                        mAdSplashManager.loadAd(mAdUnitId, isFullScreenMode() ? 0 : rltBottom.getHeight(),getBottomAdCodeId(),getScenarioId());
                    }
                }else{
                    toMainByDelay(false);
                }
            }

            @Override
            public void onFetchAdError() {
                toMainByDelay(false);
            }
        });

    }
    private void initCutDown() {
        txtVipSkip.setVisibility(View.GONE);
        txtVipSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    startActivity(getVipActivity());
                } catch (Exception e) {
                }
            }
        });
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toMainByDelay(true);
            }
        });
    }

    private void showCutDown() {
        try {
            if(handlerCloseSplash!=null){
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (txtSkip.getVisibility() == View.VISIBLE) {
            return;
        }
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if(isHideSkipBtn()){
            txtSkip.setVisibility(View.GONE);
        }else {
            txtSkip.setVisibility(View.VISIBLE);
        }
    }

    public void autoCloseSplash() {
        //未知情况出现卡死的情况下，主动执行跳转
        try {
            if(handlerCloseSplash!=null){
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = new Handler();
        handlerCloseSplash.postDelayed(new Runnable() {
            @Override
            public void run() {
                ADUtil.logError("是否需要自动关闭："+!isAdShown);
                if (!isAdShown) {
                    if (!isFinishing()) {
                        ADUtil.logError("=====执行自动关闭=====");
                        toMain();
                    }
                }
            }
        }, getSplashCloseDelayTimeInNoAd());
    }

    private void initListener() {
        mAdInteractionListener = new TTSplashAd.AdInteractionListener() {

            @Override
            public void onAdClicked(View view, int i) {
                ADUtil.logError("开屏广告被点击");
                isClickAd = true;
            }

            @Override
            public void onAdShow(View view, int i) {

                isAdShown = true;
                if (isFullScreenMode()) {
                    rltBottom.setVisibility(View.GONE);
                } else {
                    rltBottom.setVisibility(View.VISIBLE);
                }
                showCutDown();
                ADUtil.setFirstUseAdTime();
                ADUtil.logError("开屏广告显示");
                MediationAdEcpmInfo gmAdEcpmInfo = null;
                try {
                    gmAdEcpmInfo = mAdSplashManager.getSplashAd().getMediationManager().getShowEcpm();
                    ADUtil.logError("当前开屏SdkName："+gmAdEcpmInfo.getSdkName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getSplashYlhErrorInfo();
                SplashAD ylhSplashAD = ADManager.getInstance().getYlhSplashAD();
                KsErrorInfo ksErrorInfo = ADManager.getInstance().getSplashKsErrorInfo();
                KsSplashScreenAd ksSplashAD = ADManager.getInstance().getKsSplashAd();
                if(gmAdEcpmInfo!=null){
                    if(ylhErrorInfo!=null&&ylhSplashAD!=null&&
                            !ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())){
                        int ecpm = getReportEcmp(ylhSplashAD.getECPM(),gmAdEcpmInfo.getEcpm());
                        ylhSplashAD.sendLossNotification(ecpm,ylhErrorInfo.getReason(),ylhErrorInfo.getAdnId());
                        ADUtil.logError("上报优量汇开屏竞价失败：ecpm="+ecpm+"，"+ylhErrorInfo);
                    }
                    if(ksErrorInfo!=null&&ksSplashAD!=null&&
                            !ADManager.getInstance().isKsPlatform(gmAdEcpmInfo.getSdkName())){
                        if(ksErrorInfo.getAdExposureFailedReason()!=null){
                            ksErrorInfo.getAdExposureFailedReason().setWinEcpm(getReportEcmp(ksSplashAD.getECPM(),gmAdEcpmInfo.getEcpm()))
                                    .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                        }
                        ksSplashAD.reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(),ksErrorInfo.getAdExposureFailedReason());
                        ADUtil.logError("上报快手开屏竞价失败："+ksErrorInfo);
                    }
                }
                ADManager.getInstance().clearCurrentSplash();
            }

            @Override
            public void onAdSkip() {
                ADUtil.logError("onAdSkip");
                toNext();
            }

            @Override
            public void onAdTimeOver() {
                ADUtil.logError("=====广告显示结束=====");
                toNext();
            }

        };
    }
    private int getReportEcmp(int lossEcpm,String winEcpm){
        int ecpm = lossEcpm;
        try {
            if(ecpm<=0){
                ecpm = 20 * ADConst.YUAN;
            }
            double preEcpm = Double.parseDouble(winEcpm);
            if(preEcpm>0) {
                ecpm = (int) (preEcpm + 1* ADConst.YUAN);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ecpm;
    }

    private void initAdLoader() {
        mAdSplashManager = new AdSplashManager(this, mAdInteractionListener, new TTAdNative.SplashAdListener() {
            @Override
            public void onError(int i, String s) {
                ADUtil.logError("聚合开屏加载失败 : " + i + ", " + s);
                // 获取本次waterfall加载中，加载失败的adn错误信息。
                if (mAdSplashManager.getSplashAd() != null) {
                    try {
                        ADUtil.logError("聚合开屏加载失败数据: " + mAdSplashManager.getSplashAd().getMediationManager().getAdLoadInfo());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                toMainByDelay(false);

            }

            @Override
            public void onTimeout() {
                toNext();
            }

            @Override
            public void onSplashAdLoad(TTSplashAd ttSplashAd) {

                ADUtil.logError("====聚合开屏加载成功====");
                mAdSplashManager.showSplashAd(splash_container,ttSplashAd);
                SplashShownManager.getInstance().setSplashShown(true);
                mAdSplashManager.printInfo();
            }
        });
    }

    private void toNext() {
        if (!isDealToNext) {
            next();
        }
        isDealToNext = true;
    }

    private void toMainByDelay(boolean isNowSkip) {
        if (isNowSkip) {
            ADUtil.logError("=====执行立即跳转=====");
            toMain();
        } else {
            long delay = getDelayFinishTime();
            ADUtil.logError("=====执行延时跳转====="+delay);
            toMain(delay);
        }
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isForceClose = true;
    }

    @Override
    protected void onResume() {
        if(isForceClose&&isClickAd){
            toMain();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAdSplashManager != null) {
            mAdSplashManager.destroy();
        }
        try {
            if (handlerCloseSplash != null) {
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = null;
    }

    protected long getSplashCloseDelayTimeInNoAd() {
        return 6000;
    }

    protected String getScenarioId() {
        return null;
    }

    public abstract String getAdUnitId();

    public abstract String getBottomAdCodeId();

    public abstract boolean isFullScreenMode();

    public abstract boolean isShowVipSkipBtn();

    public abstract Class<?> getVipActivity();

    protected abstract boolean isHideSkipBtn();
}
